package com.ds.robot.assistant.service.yunxiao;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.devops20210625.AsyncClient;
import com.google.common.cache.LoadingCache;
import com.ds.robot.assistant.component.MessageSender;
import com.ds.robot.assistant.entity.ProjectInfoEntity;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 *
 */
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class YunXiaoBase {

    public static final String ORGANIZATION_ID = "662*****";

    public static final String BUG_FORMART = "https://devops.aliyun.com/projex/project/%s/bug";

    public static final String REQ_FORMART = "https://devops.aliyun.com/projex/project/%s/req";

    public static final String TAG_EMPTY = "未打标签";
    public static final String STR_PROJECT = "Project";
    public static final String MAX_RESULTS = "200";

    public AtomicInteger dayThreshold = new AtomicInteger(10);

    protected static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    protected static final LinkedHashMap<String, String> PROJECT_MAP = new LinkedHashMap<>();

    static {
        PROJECT_MAP.put("889ea8b1980f95b17a579997e1", "用户端项目");
        PROJECT_MAP.put("cf8fb2a10735bc3bbc03542ded", "店长端项目");
        PROJECT_MAP.put("04f1d60c341235d554b05110d1", "供应链ERP项目");
        PROJECT_MAP.put("f482e061475581b1915cbf81d2", "营销中台项目");
        PROJECT_MAP.put("9dee251a92fa4415486d4a8847", "加盟商平台项目");
        PROJECT_MAP.put("175179f7cebea8804f8618de2c", "其它项目");
    }


    public static final List<String> STATE_ORDER_LIST = Arrays.asList("待确认", "待处理", "处理中", "开发中", "开发完成", "再次打开", "重新打开");

    @Resource
    protected LoadingCache<String, String> userCache;

    @Resource
    protected LoadingCache<String, ProjectInfoEntity> projectCache;

    protected static final HashMap<String, String> USER_MAP = new HashMap<String, String>() {
        private static final long serialVersionUID = 9177799138103076651L;

        {
            put("208717223442543221", "杨*");
            put("208717223442543222", "刘*");
            put("208717223442543223", "王**");
        }
    };

    protected static final int MAX_POOL_SIZE = Math.max(2 * Runtime.getRuntime().availableProcessors(), 4);

    protected static final ExecutorService apiExecutor = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            MAX_POOL_SIZE,
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    @Autowired
    protected MessageSender messageSender;

    @Value("${aliyun.api.accessKeyId}")
    protected String accessKeyId;

    @Value("${aliyun.api.accessKeySecret}")
    protected String accessKeySecret;

    // Configure the Client
    protected AsyncClient asyncClient;

    @PostConstruct
    protected void init() {
        // log.info("====阿里云：{}, {}", accessKeyId, accessKeySecret);
        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider PROVIDER = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                // .securityToken(System.getenv("SECURITY_TOKEN")) // use STS token
                .build());

        asyncClient = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(PROVIDER)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/devops
                                .setEndpointOverride("devops.cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                ).build();
    }


    @NotNull
    protected LinkedHashMap<String, String> getProjectMap() {
        LinkedHashMap<String, String> projectMap = PROJECT_MAP;
        ConcurrentMap<String, ProjectInfoEntity> concurrentMap = projectCache.asMap();
        if (Objects.nonNull(concurrentMap) && concurrentMap.size() >= PROJECT_MAP.size()) {
            projectMap = concurrentMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getName(), (o, n) -> o, LinkedHashMap::new));
        }
        return projectMap;
    }

}
